package com.loong.web.suppert.handle;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.env.ConfigurablePropertyResolver;

import com.loong.tool.secret.security.encrypt.Symmetric;

/**
 * 配置文件加载器
 * 
 * @author 张成轩
 */
public class ConfigurerHandler extends PropertySourcesPlaceholderConfigurer implements Converter<String, String> {

	private static final String KEY = System.getenv("GP4J_KEY");

	private static final String CRYPTO_START = "=";

	@Override
	protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess,
			ConfigurablePropertyResolver propertyResolver) throws BeansException {

		propertyResolver.getConversionService().addConverter(this);
		super.processProperties(beanFactoryToProcess, propertyResolver);
	}

	@Override
	public String convert(String source) {

		// 配置文件解密
		if (source.startsWith(CRYPTO_START) && KEY != null)
			source = Symmetric.decrypt(source.substring(CRYPTO_START.length()), KEY);
		return source;
	}
}
